extends Sprite2D

@export var speed = 0.08
@export var target: Node2D 
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	$AnimationPlayer.play("BW_Run")
	pass # Replace with function body.

var lastMove = false
var wait_time = 0.5
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	var curpos = self.position
	var offset = Vector2(0,0)
	var move = false
	###判定与目标距离大于10 则跟随目标移动 否则停止移动#
	if target:
		var targetpos = target.position
		var dis = curpos.distance_to(targetpos)
		if dis > 50:
			wait_time -= delta
			if wait_time < 0:
				offset = (targetpos - curpos).normalized() * 10 * speed
				move = true
		else:
			wait_time = 0.5
			move = false
			
	#判定左右方向 设定scale.x 来控制方向#
	if move and offset.x > 0:
		scale.x = 1
	elif move and offset.x < 0:
		scale.x = -1
	

	# if Input.is_action_pressed("up_move"):
	# 	offset.y -= 10 * speed
	# 	move = true
	# elif  Input.is_action_pressed("down_move"):
	# 	offset.y += 10 * speed
	# 	move = true
	# elif  Input.is_action_pressed("left_move"):
	# 	offset.x -= 10 * speed
	# 	move = true
	# 	scale.x = -1
	# elif  Input.is_action_pressed("right_move"):
	# 	offset.x += 10 * speed
	# 	move = true
	# 	scale.x = 1
	#var cell = grid.local_to_map(position+offset)
	self.position += offset
	if move and lastMove!= move:
		$AnimationPlayer.play("BW_Run")

	if not move and lastMove!= move:
		$AnimationPlayer.play("BW_Idle")	
	lastMove = move
	pass
